/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fast.framework.web.core;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fast.framework.constant.Constant;
import com.fast.framework.web.handler.ActionHandler;
import com.fast.framework.web.session.RequestManager;

/**
 * jfast核心处理器
 * @author zengjintao
 * @version 1.0
 * 2017年10月15日下午9:54:28
 */
@WebServlet(urlPatterns="/*",loadOnStartup = 0)
public class CoreHttpServlet extends HttpServlet {
	
	private static final RequestManager requestManger = RequestManager.getRequestManger();
	
	private int contextPathLength;
	
	private static final ActionHandler actionHandler = ActionHandler.me();
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		String contextPath = servletConfig.getServletContext().getContextPath();//  /Jfast
		contextPathLength = (contextPath == null || "/".equals(contextPath) ? 0 : contextPath.length());
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding(Constant.CODING);
		response.setCharacterEncoding(Constant.CODING);
		String target = request.getRequestURI();//
		if (contextPathLength != 0) {
			target = target.substring(contextPathLength);
		}
		try {
			requestManger.handle(request, response);
			actionHandler.doHandler(target, request, response);//开始action请求
		} catch (Exception e) {
			throw new RuntimeException();
		}finally {
			requestManger.release();
		}
	}
}
